import {
    createBrowserRouter, Navigate,
    RouterProvider,
} from "react-router-dom";
import routes from "@/router/index.js";
import React, {Suspense} from "react";


const isAuthenticated = !!JSON.parse(localStorage.getItem('token'))
const routesMapCallBack = (routes1, level = 1) => {
    return routes1.map(route => {
        let Component = React.lazy(route.component)
        if (route.children && route.children.length > 0 && level < 10) {
            if (level === 1) {
                return {
                    path: route.path,
                    // element: <Component/>,
                    element: isAuthenticated ? <Component/> : <Navigate to="/login"/>,
                    errorElement: <div>404</div>,
                    children: routesMapCallBack(route.children, level + 1),
                };
            } else {
                if (route.component) {
                    return {
                        path: route.path,
                        element: <Component/>,
                        children: routesMapCallBack(route.children, level + 1),
                    };
                } else {
                    return {
                        path: route.path,
                        children: routesMapCallBack(route.children, level + 1),
                    };
                }

            }

        } else {
            return {
                path: route.path,
                element: <Component/>
            };
        }
    });
}
const routesMap = routesMapCallBack(routes)
const router = createBrowserRouter(routesMap)
const App = () => {
    return (
        <Suspense>
            <RouterProvider router={router}/>
        </Suspense>
    )
}

export default App
